package com.socialsoftware.model;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverter;
import androidx.room.TypeConverters;
import androidx.sqlite.db.SupportSQLiteDatabase;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// Update database version to 2 and add FriendRequest entity
@Database(entities = {Contact.class, User.class, FriendRequest.class}, version = 2, exportSchema = false)
@TypeConverters({AppDatabase.DateConverter.class})
public abstract class AppDatabase extends RoomDatabase {
    
    public abstract ContactDao contactDao();
    public abstract UserDao userDao();
    public abstract FriendRequestDao friendRequestDao();
    
    private static volatile AppDatabase INSTANCE;
    private static final int NUMBER_OF_THREADS = 4;
    public static final ExecutorService databaseWriteExecutor =
            Executors.newFixedThreadPool(NUMBER_OF_THREADS);
    
    public static AppDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(
                            context.getApplicationContext(),
                            AppDatabase.class, 
                            "socialsoftware_database")
                            .addCallback(sRoomDatabaseCallback)
                            // Always allow destructive migration to avoid version issues
                            .fallbackToDestructiveMigration()
                            .build();
                }
            }
        }
        return INSTANCE;
    }
    
    /**
     * Override the onCreate method to populate the database.
     * For this sample, we clear the database every time it is created.
     */
    private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() {
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
            
            // Populate the database in the background when first created
            databaseWriteExecutor.execute(() -> {
                try {
                // Add default special contacts and mock data
                ContactDao contactDao = INSTANCE.contactDao();
                UserDao userDao = INSTANCE.userDao();
                FriendRequestDao friendRequestDao = INSTANCE.friendRequestDao();
                
                // Clear existing data
                contactDao.deleteAll();
                userDao.deleteAll();
                friendRequestDao.deleteAll();
                
                // Add mock users
                List<User> users = createMockUsers();
                for (User user : users) {
                    userDao.insert(user);
                }
                
                // Add only special contacts (like "New Friends", "Groups", etc.)
                // Regular contacts will be fetched from server during login
                List<Contact> specialContacts = createSpecialContacts();
                contactDao.insertAll(specialContacts);
                
                // Note: Friend requests are now fetched from server during login
                // and not created statically here
                } catch (Exception e) {
                    // Log error but don't crash
                    android.util.Log.e("AppDatabase", "Error populating database: " + e.getMessage(), e);
                }
            });
        }
    };
    
    /**
     * Create mock users for demo purposes
     */
    private static List<User> createMockUsers() {
        List<User> users = new ArrayList<>();
        
        // Add mock users
        User currentUser = new User("user_123", "user", "Demo User", "avatar_self");
        currentUser.setEmail("user@example.com");
        currentUser.setPhoneNumber("123-456-7890");
        currentUser.setStatus("Available");
        currentUser.setLastSeen(System.currentTimeMillis());
        users.add(currentUser);
        
        return users;
    }
    
    /**
     * Create special contacts for the contacts list
     * These are fixed entries like "New Friends", "Groups", etc.
     */
    private static List<Contact> createSpecialContacts() {
        List<Contact> contacts = new ArrayList<>();
        
        // Special contacts (like in WeChat)
        contacts.add(new Contact(Contact.TYPE_SPECIAL, "新的朋友", "new_friends_icon"));
        contacts.add(new Contact(Contact.TYPE_SPECIAL, "群聊", "group_chat_icon"));
        contacts.add(new Contact(Contact.TYPE_SPECIAL, "标签", "tags_icon"));
        contacts.add(new Contact(Contact.TYPE_SPECIAL, "公众号", "official_accounts_icon"));
        
        return contacts;
    }
    
    /**
     * TypeConverter for Date objects
     */
    public static class DateConverter {
        @TypeConverter
        public static Date fromTimestamp(Long value) {
            return value == null ? null : new Date(value);
        }
        
        @TypeConverter
        public static Long dateToTimestamp(Date date) {
            return date == null ? null : date.getTime();
        }
    }
} 